//
//  SpecialVC.m
//  SHNet
//
//  Created by FranklinPhill on 15/12/17.
//  Copyright © 2015年 Fire. All rights reserved.
//

#import "SpecialVC.h"
#import "JsBridge.h"

@interface SpecialVC () <UIWebViewDelegate, WebViewApiDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *contentView;
@property (strong, nonatomic) UIWebView *indexWebView;
@property (strong, nonatomic) UIWebView *categoryWebView;
@property (strong, nonatomic) UIWebView *activityWebView;
@property (strong, nonatomic) UIWebView *carWebView;
@property (strong, nonatomic) UIWebView *mineWebView;

@property (strong, nonatomic) UIButton *indexBtn;
@property (strong, nonatomic) UIButton *categoryBtn;
@property (strong, nonatomic) UIButton *activityBtn;
@property (strong, nonatomic) UIButton *carBtn;
@property (strong, nonatomic) UIButton *mineBtn;

@property (assign, nonatomic) NSInteger finishedCount;

@property (strong, nonatomic) JsBridge *bridge;

@end

@implementation SpecialVC

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog(@"viewDidLoad");
    self.finishedCount = 0;
    [self setLeftBtnHidden:YES];
    [self setRightBtnHidden:YES];
    [self setBarTitle:@"首页"];
    [self createWebViews];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    _contentView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)createWebViews {
    self.indexWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0.f, 0.f, kViewWidth, kViewHeight - 49)];
    _indexWebView.scrollView.backgroundColor = [UIColor whiteColor];
    _indexWebView.scalesPageToFit = YES;
    _indexWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    _indexWebView.delegate = self;
    NSURL *url = [NSURL URLWithString:@"http://bbs.sh0951.com/wap/jingdong/pages/index.html"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [_indexWebView loadRequest:request];
    
    self.categoryWebView = [[UIWebView alloc] initWithFrame:CGRectMake(kViewWidth, 0.f, kViewWidth, kViewHeight - 49)];
    _categoryWebView.scrollView.backgroundColor = [UIColor whiteColor];
    _categoryWebView.scalesPageToFit = YES;
    _categoryWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    _categoryWebView.delegate = self;
    NSURL *url1 = [NSURL URLWithString:@"http://bbs.sh0951.com/wap/jingdong/pages/category.html"];
    NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1];
    [_categoryWebView loadRequest:request1];
    
    self.activityWebView = [[UIWebView alloc] initWithFrame:CGRectMake(kViewWidth * 2, 0.f, kViewWidth, kViewHeight - 49)];
    _activityWebView.scrollView.backgroundColor = [UIColor whiteColor];
    _activityWebView.scalesPageToFit = YES;
    _activityWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    _activityWebView.delegate = self;
    NSURL *url2 = [NSURL URLWithString:@"http://bbs.sh0951.com/wap/jingdong/pages/index.html"];
    NSMutableURLRequest *request2 = [NSMutableURLRequest requestWithURL:url2];
    [_activityWebView loadRequest:request2];
    
    self.carWebView = [[UIWebView alloc] initWithFrame:CGRectMake(kViewWidth * 3, 0.f, kViewWidth, kViewHeight - 49)];
    _carWebView.scrollView.backgroundColor = [UIColor whiteColor];
    _carWebView.scalesPageToFit = YES;
    _carWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    _carWebView.delegate = self;
    NSURL *url3 = [NSURL URLWithString:@"http://bbs.sh0951.com/wap/jingdong/pages/cart.html"];
    NSMutableURLRequest *request3 = [NSMutableURLRequest requestWithURL:url3];
    [_carWebView loadRequest:request3];
    
    self.mineWebView = [[UIWebView alloc] initWithFrame:CGRectMake(kViewWidth * 4, 0.f, kViewWidth, kViewHeight - 49)];
    _mineWebView.scrollView.backgroundColor = [UIColor whiteColor];
    _mineWebView.scalesPageToFit = YES;
    _mineWebView.dataDetectorTypes = UIDataDetectorTypeNone;
    _mineWebView.delegate = self;
    NSURL *url4 = [NSURL URLWithString:@"http://bbs.sh0951.com/wap/jingdong/pages/personal.html"];
    NSMutableURLRequest *request4 = [NSMutableURLRequest requestWithURL:url4];
    [_mineWebView loadRequest:request4];
    
    _indexWebView.opaque = YES;
    _categoryWebView.opaque = YES;
    _activityWebView.opaque = YES;
    _carWebView.opaque = YES;
    _mineWebView.opaque = YES;
    
    [_contentView addSubview:_indexWebView];
    [_contentView addSubview:_categoryWebView];
    [_contentView addSubview:_activityWebView];
    [_contentView addSubview:_carWebView];
    [_contentView addSubview:_mineWebView];
    
    [self createBtn];
}

- (void)createBtn {
    self.indexBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _indexBtn.frame = _indexWebView.frame;
    _indexBtn.backgroundColor = [UIColor whiteColor];
    [_indexBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateNormal];
    [_indexBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateHighlighted];
    _indexBtn.opaque = YES;
    _indexBtn.hidden = YES;
    [_indexBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.categoryBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _categoryBtn.frame = _categoryWebView.frame;
    _categoryBtn.backgroundColor = [UIColor whiteColor];
    [_categoryBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateNormal];
    [_categoryBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateHighlighted];
    _categoryBtn.opaque = YES;
    _categoryBtn.hidden = YES;
    [_categoryBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.activityBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _activityBtn.frame = _activityWebView.frame;
    _activityBtn.backgroundColor = [UIColor whiteColor];
    [_activityBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateNormal];
    [_activityBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateHighlighted];
    _activityBtn.opaque = YES;
    _activityBtn.hidden = YES;
    [_activityBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.carBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _carBtn.frame = _carWebView.frame;
    _carBtn.backgroundColor = [UIColor whiteColor];
    [_carBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateNormal];
    [_carBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateHighlighted];
    _carBtn.opaque = YES;
    _carBtn.hidden = YES;
    [_carBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    self.mineBtn = [[UIButton alloc] init];
    _mineBtn.frame = _mineWebView.frame;
    _mineBtn.backgroundColor = [UIColor whiteColor];
    [_mineBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateNormal];
    [_mineBtn setImage:[UIImage imageNamed:@"loading_failed"] forState:UIControlStateHighlighted];
    _mineBtn.opaque = YES;
    _mineBtn.hidden = YES;
    [_mineBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [_contentView insertSubview:_indexBtn aboveSubview:_indexWebView];
    [_contentView insertSubview:_categoryBtn aboveSubview:_categoryWebView];
    [_contentView insertSubview:_activityBtn aboveSubview:_activityWebView];
    [_contentView insertSubview:_carBtn aboveSubview:_carWebView];
    [_contentView insertSubview:_mineBtn aboveSubview:_mineWebView];
}

#pragma mark - UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [SHUIToolkit showLoadingInView:self.view withTitle:@"请稍候..."];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [SHUIToolkit hideLoadingMessageInView:self.view];
    if ([webView isEqual:_indexWebView]) {
        DLog(@"_indexwebview done");
        _indexBtn.hidden = YES;
    }
    else if ([webView isEqual:_categoryWebView]) {
        DLog(@"_categoryWebView done");
        _categoryBtn.hidden = YES;
    }
    else if ([webView isEqual:_activityWebView]) {
        DLog(@"_activityWebView done");
        _activityBtn.hidden = YES;
    }
    else if ([webView isEqual:_carWebView]) {
        DLog(@"_carWebView done");
        _carBtn.hidden = YES;
    }
    else if ([webView isEqual:_mineWebView]) {
        DLog(@"_mineWebView done");
        _mineBtn.hidden = YES;
    }
    self.finishedCount++;
    DLog(@"finished count:%ld", _finishedCount);
    if (_finishedCount == 5) {
        DLog(@"加载完毕");
        [[NSNotificationCenter defaultCenter] postNotificationName:webViewLoadFinishedNotification object:nil];
    }
}

/*
 NS_ENUM(NSInteger)
 {
 NSURLErrorUnknown = 			-1,
 NSURLErrorCancelled = 			-999,
 NSURLErrorBadURL = 				-1000,
 NSURLErrorTimedOut = 			-1001,
 NSURLErrorUnsupportedURL = 			-1002,
 NSURLErrorCannotFindHost = 			-1003,
 NSURLErrorCannotConnectToHost = 		-1004,
 NSURLErrorNetworkConnectionLost = 		-1005,
 NSURLErrorDNSLookupFailed = 		-1006,
 NSURLErrorHTTPTooManyRedirects = 		-1007,
 NSURLErrorResourceUnavailable = 		-1008,
 NSURLErrorNotConnectedToInternet = 		-1009,
 NSURLErrorRedirectToNonExistentLocation = 	-1010,
 NSURLErrorBadServerResponse = 		-1011,
 NSURLErrorUserCancelledAuthentication = 	-1012,
 NSURLErrorUserAuthenticationRequired = 	-1013,
 NSURLErrorZeroByteResource = 		-1014,
 NSURLErrorCannotDecodeRawData =             -1015,
 NSURLErrorCannotDecodeContentData =         -1016,
 NSURLErrorCannotParseResponse =             -1017,
 NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
 NSURLErrorFileDoesNotExist = 		-1100,
 NSURLErrorFileIsDirectory = 		-1101,
 NSURLErrorNoPermissionsToReadFile = 	-1102,
 NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =	-1103,
 
 // SSL errors
 NSURLErrorSecureConnectionFailed = 		-1200,
 NSURLErrorServerCertificateHasBadDate = 	-1201,
 NSURLErrorServerCertificateUntrusted = 	-1202,
 NSURLErrorServerCertificateHasUnknownRoot = -1203,
 NSURLErrorServerCertificateNotYetValid = 	-1204,
 NSURLErrorClientCertificateRejected = 	-1205,
 NSURLErrorClientCertificateRequired =	-1206,
 NSURLErrorCannotLoadFromNetwork = 		-2000,
 
 // Download and file I/O errors
 NSURLErrorCannotCreateFile = 		-3000,
 NSURLErrorCannotOpenFile = 			-3001,
 NSURLErrorCannotCloseFile = 		-3002,
 NSURLErrorCannotWriteToFile = 		-3003,
 NSURLErrorCannotRemoveFile = 		-3004,
 NSURLErrorCannotMoveFile = 			-3005,
 NSURLErrorDownloadDecodingFailedMidStream = -3006,
 NSURLErrorDownloadDecodingFailedToComplete =-3007,
 
 NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
 NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
 NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
 NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,
 
 NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
 NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
 NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
 };
 */
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error {
    [SHUIToolkit hideLoadingMessageInView:self.view];
    if ([webView isEqual:_indexWebView]) {
        DLog(@"首页加载失败:%@", error);
        _indexBtn.hidden = NO;
    }
    else if ([webView isEqual:_categoryWebView]) {
        DLog(@"分类加载失败:%@", error);
        _categoryBtn.hidden = NO;
    }
    else if ([webView isEqual:_activityWebView]) {
        DLog(@"活动加载失败:%@", error);
        _activityBtn.hidden = NO;
    }
    else if ([webView isEqual:_carWebView]) {
        DLog(@"购物车加载失败:%@", error);
        _carBtn.hidden = NO;
    }
    else if ([webView isEqual:_mineWebView]) {
        DLog(@"我的加载失败:%@", error);
        _mineBtn.hidden = NO;
    }
    self.finishedCount++;
    if (_finishedCount == 5) {
        DLog(@"加载完毕");
        [[NSNotificationCenter defaultCenter] postNotificationName:webViewLoadFinishedNotification object:nil];
    }
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger pageCount = 0;
    switch (item.tag) {
        case 2000: pageCount = 0; [self setBarTitle:@"首页"]; break;
        case 2001: pageCount = 1; [self setBarTitle:@"分类"]; break;
        case 2002: pageCount = 2; [self setBarTitle:@"活动"]; break;
        case 2003: pageCount = 3; [self setBarTitle:@"购物车"]; break;
        case 2004: pageCount = 4; [self setBarTitle:@"我的"]; break;
        default: pageCount = 0; break;
    }
    [_contentView setContentOffset:CGPointMake((pageCount) * kViewWidth, 0.f)];
}

- (void)btnClicked:(UIButton *)sender {
    sender.hidden = YES;
    if ([sender isEqual:_indexBtn]) {
        [_indexWebView reload];
    }
    else if ([sender isEqual:_categoryBtn]) {
        [_categoryWebView reload];
    }
    else if ([sender isEqual:_activityBtn]) {
        [_activityWebView reload];
    }
    else if ([sender isEqual:_carBtn]) {
        [_carWebView reload];
    }
    else if ([sender isEqual:_mineBtn]) {
        [_mineWebView reload];
    }
}

#pragma mark - JavaScript Bridge

- (void)invoke:(JsBridge *)bridge api:(NSString *)api callback:(WVJBResponseCallback)callback withArgs:(NSDictionary *)args reqCode:(NSNumber *)code {
    DLog(@"api:%@", api);
    if ([api isEqualToString:@"jumpToPage"]) {
        
    }
}

- (NSArray *)getWebApiNames {
    NSMutableArray *apis = [[NSMutableArray alloc] initWithObjects:@"jumpToPage", @"close_activity", @"go_back", @"go_back_reload", @"call", @"sms" , @"choose_image", @"barcode_scan", @"get_login_user", @"get_vs_status", @"open_url", @"check_vs", @"set_value", @"start_singleton_page", @"reload", @"remove_login_info", @"progress", @"get_nas_info", @"ap_invoke", @"go_website", @"get_ap_msg", @"go_wechat", nil];
    return [NSArray arrayWithArray:apis];
}

@end
